<?php
namespace app\index\controller;

use app\common\logic\WechatLogic;
use think\Db;

class Author
{
    public function index(){
        file_put_contents('./requestMsg.log', '微信访问记录:'.date('Y-m-d : h:i:sa',time())."\n", FILE_APPEND);
        include_once(EXTEND_PATH.'wxcrypt/wxBizMsgCrypt.php');
        $wehcat = Db::name('wx_user')->find();
        $encodingAesKey = $wehcat['encoding_aes_key']; 
        $token = $wehcat['w_token'];
        $appId = $wehcat['appid'];

        $timeStamp  = empty($_GET['timestamp'])     ? ""    : trim($_GET['timestamp']) ;
        $nonce      = empty($_GET['nonce'])     ? ""    : trim($_GET['nonce']) ;
        $msg_sign   = empty($_GET['msg_signature']) ? ""    : trim($_GET['msg_signature']) ;
        $encryptMsg = file_get_contents('php://input');
        $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);

        $xml_tree = new \DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;

        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);
//         logResult('/form.log', $from_xml);

        // 第三方收到公众号平台发送的消息
        $msg = '';
        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        
        if ($errCode == 0) {
            //print("解密后: " . $msg . "\n");
            $xml = new \DOMDocument();
            $xml->loadXML($msg);

            $array_infotype = $xml->getElementsByTagName('InfoType');
            if($array_infotype && $array_infotype->item(0)->nodeValue == 'unauthorized'){
                //公众号取消授权
                $array_authorizerAppid = $xml->getElementsByTagName('AuthorizerAppid');
                $authorizerAppid = $array_authorizerAppid->item(0)->nodeValue;
                Db::name('author_wx_user')->where('appid',$authorizerAppid)->update(['authorized' => 0]);
                Db::name('users')->query("DELETE FROM `think_users` WHERE  `auid` = (SELECT `id` FROM `think_author_wx_user` WHERE `appid` = '{$authorizerAppid}')");
                return true;
            }
            
            $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
            $component_verify_ticket = $array_e->item(0)->nodeValue;
            file_put_contents(ROOT_PATH.'/ticket.log', $component_verify_ticket);
            $this->logResult('/msgmsg.log','解密后的component_verify_ticket是：'.$component_verify_ticket);

            Db::name('wx_user')->where('id',$wehcat['id'])->update(['component_verify_ticket' => $component_verify_ticket]);
            // echo 'success';
        
        } else {
            $this->logResult('/error.log','解密后失败：'.$errCode);
            print($errCode . "\n");
        }
    }

    public function logResult($path,$data){
        file_put_contents(ROOT_PATH.$path, '['.date('Y-m-d : h:i:sa',time()).']'.$data."\r\n",FILE_APPEND);
    }
}